package com.bw.module_home.widget

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import android.util.Log
import android.view.View
import com.bw.module_home.R

/**
 * @author ytx
 * @date 2025-10-18 08:08
 * @description
 */
class RedPacketView: View {
    //画笔
    private val bgPaint = Paint() //背景圆环画笔
    private val fgPaint = Paint() //前景圆环进度画笔
    private val bitmapPaint = Paint() //图片画笔

    private val paintWidth = 10f //画笔粗细
    private var angle = 0f//扫描角度

    //圆环区域
    private val rectF = RectF()
    //图片区域
    private lateinit var bitmap: Bitmap//图片
    private val srcRect = Rect() //自身区域
    private val dstRect = Rect() //位置区域

    /**
     * 默认宽高
     */
    private val defaultWidth = 150 //dp转px
    private val defaultHeight = 150

    /**
     * 动画
     */
    private var valueAnimator:ValueAnimator? = null



    constructor(context: Context?) : this(context,null)
    constructor(context: Context?, attrs: android.util.AttributeSet?) : this(context, attrs,0)
    constructor(context: Context?, attrs: android.util.AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr){
        initPaint()
    }

    /**
     * 初始化画笔
     */
    private fun initPaint() {
        bgPaint.apply {
            isAntiAlias = true //抗锯齿
            isDither = true //防抖动
            setColor(Color.rgb(221, 221, 221))
            style = Paint.Style.STROKE //空心
            strokeWidth = paintWidth //粗细
        }
        fgPaint.apply {
            isAntiAlias = true
            isDither = true
            setColor(Color.rgb(255, 0, 0))
            style = Paint.Style.STROKE
            strokeWidth = paintWidth
        }
        bitmapPaint.apply {
            isAntiAlias = true
            isDither = true
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        bitmap = getBitmap(R.drawable.redpacket,measuredWidth/2,measuredHeight/2)
        //圆环的区域
        rectF.apply {
            left = 0f+paintWidth
            top = 0f+paintWidth
            right = measuredWidth.toFloat() - paintWidth//当前view的宽度
            bottom = measuredHeight.toFloat() -paintWidth //当前view的高度
        }
        //图片的区域
        //自身大小
        srcRect.apply {
            left = 0
            top = 0
            right = bitmap.width
            bottom = bitmap.height
        }
        //区域位置
        dstRect.apply {
            left = measuredWidth / 2 - bitmap.width / 2
            top = measuredHeight / 2 - bitmap.height / 2
            right = measuredWidth / 2 + bitmap.width / 2
            bottom = measuredHeight / 2 + bitmap.height / 2
        }

    }

    /**
     * 绘制：背景圆环、前景圆环、图片
     * 注意事项：不要创建对象，防止内存抖动
     */
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //绘制图片
        canvas.drawBitmap(bitmap, srcRect, dstRect, bitmapPaint)
        //绘制背景圆环
        canvas.drawArc(rectF,0f,360f,false,bgPaint)
        //绘制前景扇形
        canvas.drawArc(rectF,-90f,angle,false,fgPaint)
    }

    /**
     * 测量：三种  测量规格32位=测昂模式2位+测量大小30位
     * 1.精确测量：宽高都精确测量或match
     * 2.AT_most：wrap
     * 3.UNSPECIFIED：没有限制
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var widthSize = MeasureSpec.getSize(widthMeasureSpec)
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)
        if (widthMode == MeasureSpec.AT_MOST){
            widthSize = defaultWidth
        }
        if (heightMode == MeasureSpec.AT_MOST){
            heightSize = defaultHeight
        }
        setMeasuredDimension(widthSize,heightSize) //设置测量宽度和高度
    }

    /**
     * bitmap二次采样：尺寸压缩
     */
    private fun getBitmap(id: Int,width:Int,height:Int):Bitmap{
        //第一次采样：只采集原图宽高信息，不采集像素点
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeResource(resources,id,options)
        val outWidth = options.outWidth
        val outHeight = options.outHeight
        //计算压缩比例：2的幂次方
        var sampleSize = 1
        while (outWidth/ sampleSize > width || outHeight/sampleSize > height){
            sampleSize *= 2
        }
        //第二次采样：采集像素点按照压缩比例采集
        options.inJustDecodeBounds = false
        options.inSampleSize = sampleSize //压缩比例
        val bitmap = BitmapFactory.decodeResource(resources,id,options)
        return bitmap
    }


    fun startAnimator(){
        valueAnimator = ValueAnimator.ofFloat(0f,360f)
        //添加值变化 0 - 360
        valueAnimator?.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener{
            override fun onAnimationUpdate(animation: ValueAnimator) {
                val value = animation.getAnimatedValue()
                //修改角度
                angle = value as Float
                //按照新角度绘制刷新页面
                invalidate()
            }
        })
        //监听动画，状态回调出去
        valueAnimator?.addListener(object : AnimatorListenerAdapter(){
            override fun onAnimationStart(animation: Animator) {
                super.onAnimationStart(animation)
                callBack?.start()
            }

            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                callBack?.completed() //完成
                angle = 0f
                invalidate()
                valueAnimator?.start()
            }

            override fun onAnimationPause(animation: Animator) {
                super.onAnimationPause(animation)
                callBack?.pause()
            }

            override fun onAnimationResume(animation: Animator) {
                super.onAnimationResume(animation)
                callBack?.resume()
            }
        })

        valueAnimator?.setDuration(5*1000)
        valueAnimator?.start()

    }
    fun pauseAnimator(){
        valueAnimator?.pause()

    }
    fun resumeAnimator(){
        valueAnimator?.resume()

    }
    fun stopAnimator(){
        valueAnimator?.cancel()

    }
    private var callBack:RedPacketCallBack? = null
    //接口回调
    interface RedPacketCallBack{
        fun start()
        fun pause()
        fun resume()
        fun completed()
    }
    fun setCallBack(callBack: RedPacketCallBack){
        this.callBack = callBack
    }
}